package com.liao.badminton.code.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.liao.badminton.context.BaseContextHandler;
import com.liao.badminton.dto.SystemLoginLogDto;
import com.liao.badminton.redis.RedisEnum;
import com.liao.badminton.redis.RedisUtil;
import com.liao.badminton.service.SystemLoginLogService;
import com.liao.badminton.vo.SystemUsersVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static com.liao.badminton.context.BaseContextHandler.HEADER_TTY;
import static com.liao.badminton.context.BaseContextHandler.getCurrentPort;

public class JwtTokenUtils {

    public static final String TOKEN_HEADER = "token";
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "echisan";
    // 过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 24*60 * 60L;
    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 604800L;
    private static SystemLoginLogService loginLogService = BaseContextHandler.applicationContext.getBean(SystemLoginLogService.class);


    /**
     * 使用的地方
     * 1，账号密码登录成功后，生成token并返回前端
     * 2，注册成功后，生成token并返回前端
     * 3，手机号登录成功后，生成token并返回前端
     * @param response
     * @param systemUsersVo
     * @param jwtUser
     */
    public static void setToken(HttpServletResponse response, SystemUsersVo systemUsersVo, UserDetails jwtUser) {
        String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false, jwtUser);
        RedisUtil.toSaveRedis(RedisEnum.USER_LOGIN_NAME, jwtUser.getUsername(), true);
        UsernamePasswordAuthenticationToken authenticationToken =  // 没有前端获取用户数据目前先这样写
                new UsernamePasswordAuthenticationToken(systemUsersVo,systemUsersVo.getPassword(),jwtUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        response.setHeader(JwtTokenUtils.TOKEN_HEADER, JwtTokenUtils.TOKEN_PREFIX + token);
        RedisUtil.toSaveRedis(RedisEnum.badminton_user_info_name, systemUsersVo.getUsername(), systemUsersVo);
        new Thread(() -> {
            loginLogService.handLogin(systemUsersVo.getId(),2);

        }).start();
        systemUsersVo.setPassword(null);//密码不返回给前端
    }

    // 创建token
    public static String createToken(String username, boolean isRememberMe, UserDetails jwtUser) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        HashMap<String, Object> kvHashMap = MapUtil.newHashMap();
        kvHashMap.put(username, jwtUser);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .addClaims(kvHashMap)
                .compact();
    }

    // 从token中获取用户名
    public static String getUsername(String token) {
        return getTokenBody(token).getSubject();
    }

    // 从token中获取用户信息
    public static UserDetails getUserInfo(String token) {
        Claims tokenBody = getTokenBody(token);
        Map o = (Map) tokenBody.get(tokenBody.getSubject());
        User.UserBuilder password = User.withUsername(tokenBody.getSubject()).password("");
        List<Map> authorities = (List) o.get("authorities");
        if (isNotEmpty(authorities)) {

            for (Map authoritym : authorities) {
                String authority = (String) authoritym.get("authority");
                password.authorities(authority);
            }
        }else{
            String[] array = new String[]{};
            password.authorities(array);
        }
//        return  new User(tokenBody.getSubject(), null, (Collection<? extends GrantedAuthority>) values);
        return password.build();

    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        return getTokenBody(token).getExpiration().before(new Date());
    }

    //刷新token
    public static void flushToken(String token) {
        getTokenBody(token).getExpiration().setTime(EXPIRATION);

    }

    //清除token
    public static void delToken(String token) {
        if (StrUtil.isNotBlank(token)) {
//            getTokenBody(token).clear();
            Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody().setSubject("");
        }
    }

    private static Claims getTokenBody(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}
